package com.lys.mixin.entity;

import com.lys.effect.ModEffects;
import com.lys.enchantment.ModEnchantments;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.EntityStatuses;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtElement;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;

@Mixin(LivingEntity.class)
public class LivingEntityMixin {

    LivingEntity livingEntity = (LivingEntity)(Object)this;

    //坚毅不倒冷却字段
    private int perseveranceCooldown;

    @Inject(method = "damage",at=@At(value= "INVOKE",target="Lnet/minecraft/entity/LivingEntity;isDead()Z"))
    private void injectDamage(DamageSource source, float amount, CallbackInfoReturnable<Boolean> cir){
        int perseveranceLevel = EnchantmentHelper.getEquipmentLevel(ModEnchantments.PERSEVERANCE, livingEntity);
        if (livingEntity.isDead()){
            if (this.perseveranceCooldown <= 0&&perseveranceLevel>0){
                livingEntity.addStatusEffect(new StatusEffectInstance(ModEffects.RESILIENCE,perseveranceLevel*20+20,perseveranceLevel,true,false));
                livingEntity.getWorld().sendEntityStatus(livingEntity, EntityStatuses.USE_TOTEM_OF_UNDYING);
                //设置冷却时间
                this.perseveranceCooldown = 180 * 20;
            }
            if (livingEntity.hasStatusEffect(ModEffects.RESILIENCE)){
                livingEntity.setHealth(1.0f);
            }
        }
    }

    @Inject(method = "writeCustomDataToNbt",at=@At(value="HEAD"))
    private void injectWriteCustomDataToNbt(NbtCompound nbt, CallbackInfo ci){
        nbt.putInt("perseveranceCooldown",perseveranceCooldown);
    }

    @Inject(method = "readCustomDataFromNbt",at=@At(value="HEAD"))
    private void injectreadCustomDataFromNbt(NbtCompound nbt, CallbackInfo ci){
        if (nbt.contains("perseveranceCooldown", NbtElement.INT_TYPE)){
             perseveranceCooldown = nbt.getInt("perseveranceCooldown");
        }
    }

    @Inject(method = "tick", at = @At(value = "INVOKE",target = "Lnet/minecraft/entity/LivingEntity;getStuckArrowCount()I"))
    private void injectTick(CallbackInfo ci) {
        // 每tick减少冷却时间
        if (this.perseveranceCooldown > 0) {
            this.perseveranceCooldown--;
        }
    }
}
